package com.company.huisuo.biz.activity

import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.recyclerview.widget.RecyclerView
import com.company.huisuo.base.BaseActivity
import com.company.huisuo.biz.adapter.WineCardAdapter
import com.company.huisuo.biz.adapter.WineCardItem
import com.company.huisuo.biz.dialog.SelectScriptDialog
import com.company.huisuo.biz.dialog.WineCardPrizeDialog
import com.company.huisuo.widget.CardStackLayoutManager
import com.company.huisuo.databinding.ActivityWineCardBinding
import com.lxj.xpopup.XPopup
import kotlin.random.Random

/**
 * 酒牌游戏Activity
 */
class WineCardActivity : BaseActivity<ActivityWineCardBinding>() {

    companion object {
        fun start(activity: Activity) {
            activity.startActivity(Intent(activity, WineCardActivity::class.java))
        }
    }

    private lateinit var cardAdapter: WineCardAdapter
    private lateinit var cardLayoutManager: CardStackLayoutManager
    private val handler = Handler(Looper.getMainLooper())
    private var isAnimating = false

    // 卡片总数（固定10张）
    private val cardCount = 10

    override fun initView() {
        // 初始化RecyclerView
        cardLayoutManager = CardStackLayoutManager()
        // 禁止用户手动滑动
        cardLayoutManager.canUserScroll = false
        mBinding.rvCards.layoutManager = cardLayoutManager

        cardAdapter = WineCardAdapter()
        mBinding.rvCards.adapter = cardAdapter

        // 返回按钮
        mBinding.ivBack.setOnClickListener {
            finish()
        }

        // 开始游戏按钮
        mBinding.ivStartGame.setOnClickListener {
            if (!isAnimating) {
                startGameAnimation()
            }
        }

        mBinding.llGroup1.setOnClickListener {
            chooseGroup(1)
        }
        mBinding.llGroup2.setOnClickListener {
            chooseGroup(2)
        }
        mBinding.llGroup3.setOnClickListener {
            chooseGroup(3)
        }
        mBinding.llGroup4.setOnClickListener {
            chooseGroup(4)
        }
        mBinding.ivSearch.setOnClickListener {
            //选择剧本 ambiguous_beer  暧昧啤酒

            XPopup.Builder(this).asCustom(SelectScriptDialog(this,"ambiguous_beer").apply {
                onConfirmListener = { value ->
                    println(value);
                }
            }).show()

        }
        mBinding.ivAdd.setOnClickListener {
            GameGroupActivity.start(this)
        }
    }

    override fun initData() {
        chooseGroup(2)

        // 初始化卡片数据（10张卡片）
        val cards = List(cardCount) { index ->
            WineCardItem(id = index, isFlipped = false)
        }
        cardAdapter.submitList(cards)

        // 初始化完成后，设置初始偏移量（让第一张卡片在中间）
        mBinding.rvCards.post {
            // 无需滚动，默认从位置0开始即可
            mBinding.rvCards.requestLayout()
        }
    }

    private fun chooseGroup(group: Int) {
        mBinding.apply {
            group1Left.isSelected = group == 1
            group1Right.isSelected = group == 1

            group2Left.isSelected = group == 2
            group2Right.isSelected = group == 2

            group3Left.isSelected = group == 3
            group3Right.isSelected = group == 3

            group4Left.isSelected = group == 4
            group4Right.isSelected = group == 4
        }
    }

    /**
     * 开始游戏动画
     */
    private fun startGameAnimation() {
        isAnimating = true

        // 重置所有卡片状态
        val resetCards = List(cardCount) { index ->
            WineCardItem(id = index, isFlipped = false)
        }
        cardAdapter.submitList(resetCards)

        // 随机选择一个停止位置（0-9之间）
        val randomTargetPosition = Random.nextInt(cardCount)

        mBinding.rvCards.post {
            // 获取当前中心位置
            val currentCenterPosition = cardLayoutManager.getCenterPosition()

            // 计算滚动距离：至少滚动3圈，然后停在目标位置
            val cardWidth = resources.getDimension(com.company.huisuo.R.dimen.dp_97).toInt()
            val cardSpacing = 20
            val itemTotalWidth = cardWidth + cardSpacing

            // 计算需要滚动多少个卡片：3圈 + (目标位置 - 当前位置)
            val scrollCount = 3
            val cardsToScroll =
                scrollCount * cardCount + (randomTargetPosition - currentCenterPosition + cardCount) % cardCount
            val totalScrollDistance = cardsToScroll * itemTotalWidth

            // 临时允许滚动
            cardLayoutManager.canUserScroll = true

            // 执行滚动动画
            mBinding.rvCards.smoothScrollBy(totalScrollDistance, 0)

            // 监听滚动状态，在滚动停止后执行翻牌
            mBinding.rvCards.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        // 滚动结束，禁止滚动并执行翻牌
                        cardLayoutManager.canUserScroll = false
                        recyclerView.removeOnScrollListener(this)

                        // 确保停在正确位置
                        handler.postDelayed({
                            flipCard(randomTargetPosition)
                        }, 200)
                    }
                }
            })
        }
    }

    /**
     * 翻牌动画
     */
    private fun flipCard(targetPosition: Int) {
        // 找到中心位置的View
        val centerView = findCenterCardView() ?: run {
            isAnimating = false
            return
        }

        // 获取ViewHolder，确认对应的position
        val viewHolder = mBinding.rvCards.findContainingViewHolder(centerView)
        val actualPosition = viewHolder?.bindingAdapterPosition ?: -1

        if (actualPosition < 0) {
            isAnimating = false
            return
        }

        // 获取item内部的卡片背面和正面view
        val cardBack = centerView.findViewById<View>(com.company.huisuo.R.id.iv_card_back)
        val cardFront = centerView.findViewById<View>(com.company.huisuo.R.id.cl_card_front)

        if (cardBack == null || cardFront == null) {
            isAnimating = false
            return
        }

        // 给view打标记，表示这个view已经翻开了（防止adapter覆盖）
        centerView.setTag(com.company.huisuo.R.id.iv_card_back, true)

        // 初始化正面的旋转角度（从-90度开始，这样它在背面）
        cardFront.rotationY = -90f
        cardFront.visibility = View.VISIBLE

        // 第一阶段：背面从0度旋转到90度（消失）
        val flipOutBack = ObjectAnimator.ofFloat(cardBack, "rotationY", 0f, 90f).apply {
            duration = 200
            interpolator = AccelerateDecelerateInterpolator()
        }

        // 第二阶段：正面从-90度旋转到0度（出现）
        val flipInFront = ObjectAnimator.ofFloat(cardFront, "rotationY", -90f, 0f).apply {
            duration = 200
            interpolator = AccelerateDecelerateInterpolator()
        }

        flipOutBack.addListener(object : android.animation.AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: android.animation.Animator) {
                // 背面翻转完成，隐藏背面
                cardBack.visibility = View.GONE
                // 开始正面的翻转动画
                flipInFront.start()
            }
        })

        flipInFront.addListener(object : android.animation.AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: android.animation.Animator) {
                // 动画完全结束，更新数据
                updateCardContent(targetPosition, true)
                isAnimating = false

                // 延迟300ms后调用回调，让用户有足够时间看清翻牌效果
                handler.postDelayed({
                    onAnimationComplete(targetPosition)
                }, 300)
            }
        })

        // 开始动画
        flipOutBack.start()
    }

    /**
     * 动画完全结束后的回调函数
     * @param winPosition 中奖的卡片位置(0-9)
     */
    private fun onAnimationComplete(winPosition: Int) {
        XPopup.Builder(this).asCustom(WineCardPrizeDialog(this)).show()
    }

    /**
     * 查找中心位置的卡片View
     */
    private fun findCenterCardView(): View? {
        val childCount = mBinding.rvCards.childCount
        if (childCount == 0) return null

        val centerX = mBinding.rvCards.width / 2
        var closestView: View? = null
        var minDistance = Int.MAX_VALUE

        for (i in 0 until childCount) {
            val child = mBinding.rvCards.getChildAt(i)
            val childCenterX = (child.left + child.right) / 2
            val distance = kotlin.math.abs(childCenterX - centerX)

            if (distance < minDistance) {
                minDistance = distance
                closestView = child
            }
        }

        return closestView
    }

    /**
     * 更新卡片内容
     */
    private fun updateCardContent(position: Int, isFlipped: Boolean) {
        val updatedCards = cardAdapter.items.map { item ->
            if (item.id == position) {
                item.copy(isFlipped = isFlipped)
            } else {
                item.copy(isFlipped = false)
            }
        }
        cardAdapter.submitList(updatedCards)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }
}